package com.icss.train_sys_back.controller.admin.ticket_manage;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.icss.train_sys_back.entity.ResponseResult;
import com.icss.train_sys_back.entity.ResultEnum;
import com.icss.train_sys_back.entity.home.MyTicketEntity;
import com.icss.train_sys_back.entity.ticket_manage.TicketEntity;
import com.icss.train_sys_back.entity.ticket_manage.TicketNumberEntity;
import com.icss.train_sys_back.entity.train_manage.StationEntity;
import com.icss.train_sys_back.entity.train_manage.TrainNumberEntity;
import com.icss.train_sys_back.mapper.train_manage.TrainNumberMapper;
import com.icss.train_sys_back.service.ticket_manage.TicketManageService;
import com.icss.train_sys_back.utils.PositionUtil;
import com.icss.train_sys_back.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author 小泽
 * @createTime 2025/10/2 14:12
 */
@RestController
@RequestMapping("/admin/ticket_manage")
@Slf4j
public class TicketManageController {
    @Autowired
    private TicketManageService ticketManageService;
    @Autowired
    private TrainNumberMapper trainNumberMapper;


    //车票分页+条件查询
    @GetMapping("/getList")
    public ResponseResult getListConditions(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "8") Integer pageSize,
            @RequestParam(required = false) String trainNumber,
            @RequestParam(required = false) String startStationId,
            @RequestParam(required = false) Integer endStationId,
            @RequestParam(required = false) Integer status
    ) {
        log.info("车票分页+条件查询 page = {} pageSize = {} trainNumber = {} startStationId = {}  endStationId ={} status={} ",
                page, pageSize, trainNumber, startStationId, endStationId, status);
        PageHelper.startPage(page, pageSize);
        List<TicketEntity> ticketEntityList = ticketManageService.getListConditions(trainNumber, startStationId, endStationId, status);
        PageInfo<TicketEntity> pageInfo = new PageInfo<>(ticketEntityList);
        return ResponseResult.success(pageInfo);
    }

    //更新车票信息
    @PostMapping("/update")
    public ResponseResult update(@RequestBody TicketEntity ticket) {
        log.info("更新车票信息 ticket = {}", ticket);
        ticketManageService.update(ticket);
        return ResponseResult.success();
    }

    //添加车票
    @PostMapping("/add")
    public ResponseResult add(@RequestBody TicketEntity ticket) {
        log.info("添加车票 ticket = {}", ticket);
        boolean res = ticketManageService.add(ticket);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);

    }

    //删除车票
    @DeleteMapping("/delete/{ticketId}")
    public ResponseResult delete(@PathVariable("ticketId") String ticketId) {
        log.info("删除车票 ticketId = {}", ticketId);
        boolean res = ticketManageService.deleteByTicketId(ticketId);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //更新车票状态
    @PostMapping("/changeStatus")
    public ResponseResult changeStatus(@RequestBody TicketEntity ticket) {
        log.info("更改车票状态 ticketId = {} , status = {}", ticket.getTicketId(), ticket.getTicketStatus());
        boolean res = ticketManageService.changeStatus(ticket.getTicketId(), ticket.getTicketStatus());
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }


    //查询本人车票
    @GetMapping("/listByUserId")
    public ResponseResult listByUserId(@RequestParam("userId") Integer userId) {
        log.info("查询本人车票  userId = {}", userId);
        List<MyTicketEntity> ticketEntityList = ticketManageService.listByUserId(userId);
        log.info("本人车票查询结果：{}", ticketEntityList);
        return ResponseResult.success(ticketEntityList);
    }


    //车票添加脚本
    @GetMapping("/addTicket")
    @Transactional
    public void addTicket() throws InterruptedException {
        List<TicketEntity> ticketEntityList = new ArrayList<>();
        List<TrainNumberEntity> allTrainNumberList = trainNumberMapper.findAllTrainNumberList();
        Random random = new Random();
        int j = 1;
        SnowflakeIdWorker worker = new SnowflakeIdWorker();
        for (TrainNumberEntity trainNumber : allTrainNumberList) {
            for (int i = 0; i < 6; i++) {
                //出发站Id 到达站Id
                StationEntity startStation = trainNumberMapper.findStartStationByStartStationName(trainNumber.getStartStation());
                StationEntity endStation = trainNumberMapper.findStartStationByStartStationName(trainNumber.getEndStation());
                //根据车次Id查到始发站 终点站  发车时间 到达时间
                //根据车次Id 查到票数和余票数
                if (j == 6) {
                    j = 1;
                }
                Integer carriageType = j++;//1--5的座位类型

                TicketNumberEntity ticketNumber = trainNumberMapper.getTicketNumberByTrainNumber(trainNumber.getTrainNumber(), carriageType);
                //构造车票实体 插入即可

                //=========================车票号
                //生成车票号  T + 雪花算法

                long ticketId = worker.nextId();

                String stringTicketId = String.valueOf(ticketId);
                //=========================


                //========================票价
                Integer length = PositionUtil.getDistance(startStation.getGlobalX(), startStation.getGlobalY(), endStation.getGlobalX(), endStation.getGlobalY());

                BigDecimal ticketMoney = BigDecimal.valueOf(length * 0.48);
                //根据车厢类型计算二次票价
                // 1: '一等座',
                // 2: '二等座',
                // 3: '商务座',
                // 4: '硬座',
                // 5: '硬卧',
                // 6: '软卧'
                switch (random.nextInt(6) + 1) {
                    case 1:
                        ticketMoney = ticketMoney.add(BigDecimal.valueOf(100));
                        break;
                    case 2:
                        ticketMoney = ticketMoney.add(BigDecimal.valueOf(0));
                    case 3:
                        ticketMoney = ticketMoney.add(BigDecimal.valueOf(200));
                        break;
                    case 4:
                        ticketMoney = ticketMoney.add(BigDecimal.valueOf(-50));
                        break;
                    case 5:
                        ticketMoney = ticketMoney.add(BigDecimal.valueOf(50));
                        break;
                    case 6:
                        ticketMoney = ticketMoney.add(BigDecimal.valueOf(+100));
                        break;
                }
                //========================

                TicketEntity ticket = new TicketEntity(
                        "T" + stringTicketId, trainNumber.getId(), carriageType, startStation.getStationId(), endStation.getStationId(),
                        trainNumber.getStartTime(), trainNumber.getArriveTime(), ticketMoney, ticketNumber.getAllNumbers(), ticketNumber.getRemainNumbers(), 1
                );
                ticketEntityList.add(ticket);
            }
        }

        //批量插入
        ticketManageService.batchAdd(ticketEntityList);
    }

}
